/*
Copyright (c) 2009, Young Digital Planet SA
All rights reserved.

* Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this 
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, 
  this list of conditions and the following disclaimer in the documentation 
  and/or other materials provided with the distribution.
* Neither the name of the Young Digital Planet SA nor the names of its 
  contributors may be used to endorse or promote products derived from this 
  software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
package pl.ydp.nexl.utils
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import pl.ydp.jobs.YJobs;
	import pl.ydp.jobs.basic.YJobInfo;
	import pl.ydp.nexl.INexlExtLoadMonitor;
	import pl.ydp.nexl.INexlExtensionDescription;
	import pl.ydp.nexl.Nexl;
	import pl.ydp.nexl.events.LoadExtensionEvent;
	import pl.ydp.utils.InvokeLater;
	
	/**
	 * Load all extensions in given array. Created to cooperate with
	 * INexlLibrary.list.
	 * @see pl.ydp.nexl.INexlLibrary#list()
	 */
	public class LoadExtensions implements INexlExtLoadMonitor, IEventDispatcher
	{
		private var m_extsLeft:uint;
		private var m_ok:Function;
		private var m_fail:Function;
		private var m_exts:Array;
		private var m_dispatcher:EventDispatcher;
		
		/**
		 * Create loader and register listener functions. If no listener functions
		 * are given then events are dispatched @see pl.ydp.nexl.events.LoadExtensionEvent.
		 * @param exts array of INexlExtensionDescription, extensions to load
		 * @param ok function called when all extensions sucessfully loaded<br>
		 * signature: <pre>function ok( exts:Array ):void</pre>
		 * where:<br><ul>
		 * <li><b><tt>exts</tt></b> - array of INexlExtensionDescription
		 * </ul>
		 * @param fail function called when some extension failed to load<br>
		 * signature: <pre>function fail( ext:INexlExtensionDescription, cause:String ):void</pre>
		 * where:<br><ul>
		 * <li><b><tt>ext</tt></b> - failed extensions
		 * <li><b><tt>couse</tt></b> - error message
		 * </ul>
		 */
		public function LoadExtensions( exts:Array = null, ok:Function = null, fail:Function=null ){
			m_dispatcher = new EventDispatcher(this);
			
			if(exts)
				load(exts, ok, fail);
		}
		
		/**
		 * Loads extensions.
		 */
		public function load(exts:Array, ok:Function = null, fail:Function=null):void{
			m_ok = ok;
			m_fail = fail;
			m_exts = exts;
			
			if ( exts.length==0 ) {
				// create fake job...
				var ajob:YJobInfo = new YJobInfo( "Load extensions.", Nexl.EXTENSIONS_LOAD_JOB, this );
				YJobs.applicationManager.spinOff( ajob );
				ajob.start();
				InvokeLater.invokeLater( function():void {
					dispatchSuccess();
					ajob.done();
				} );
				return;
			}
			m_extsLeft = exts.length;
			
			for each( var ext:INexlExtensionDescription in m_exts )
				ext.load( this );
		}
		
		/**
		 * @private
		 */
		public function failed( ext:INexlExtensionDescription, cause:String ):void {
			if ( m_fail!=null ) {
				m_fail( ext, cause );
				m_extsLeft = 0;
				m_fail = null;
				m_ok = null;
			}else{
				dispatchEvent(new LoadExtensionEvent(LoadExtensionEvent.FAILED, ext, cause));
			}
		}
		
		/**
		 * @private
		 */
		public function succeeded( ext:INexlExtensionDescription ):void {
			if ( (--m_extsLeft)==0 )
				dispatchSuccess();
		}
		
		protected function dispatchSuccess():void {
			if( m_ok!=null ){
				m_ok( m_exts );
			}else{
				dispatchEvent(new LoadExtensionEvent(LoadExtensionEvent.SUCCEEDED, m_exts));
			}
		}
		/**
		 * Create loader and register listener functions.
		 * @param exts array of INexlExtensionDescription, extensions to load
		 * @param ok function called when all extensions sucessfully loaded<br>
		 * signature: <pre>function ok( exts:Array ):void</pre>
		 * where:<br><ul>
		 * <li><b><tt>exts</tt></b> - array of INexlExtensionDescription
		 * </ul>
		 * @param fail function called when some extension failed to load<br>
		 * signature: <pre>function fail( ext:INexlExtensionDescription, cause:String ):void</pre>
		 * where:<br><ul>
		 * <li><b><tt>ext</tt></b> - failed extensions
		 * <li><b><tt>couse</tt></b> - error message
		 * </ul>
		 */
		public static function loadAllExtensions( extensions:Array, onOk:Function, onFail:Function ):void {
			new LoadExtensions( extensions, onOk, onFail );
		}
		
		//interface IEventDispatcher
		public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
		{
			m_dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference );
		}
		
		public function dispatchEvent(event:Event):Boolean
		{
			return m_dispatcher.dispatchEvent(event);
		}
		
		public function hasEventListener(type:String):Boolean
		{
			return m_dispatcher.hasEventListener(type);
		}
		
		public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
		{
			m_dispatcher.removeEventListener(type, listener, useCapture);
		}
		
		public function willTrigger(type:String):Boolean
		{
			return m_dispatcher.willTrigger(type);
		}
	}
}